package com.houor.device.controller;

import org.houor.utility.NumberUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.houor.device.controller.data.ControllerFrame;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class DataClientHandler extends SimpleChannelInboundHandler<ControllerFrame> {

	private static Logger logger = LoggerFactory.getLogger(DataClientHandler.class);

	private ControllerFrame msg;

	public DataClientHandler() {
		msg = new ControllerFrame();

		byte[] content = new byte[] { 0x11, 0x01, 0x00, 0x00, 0x00, 0x01 };

		msg.setLength((short) (content.length + 13));
		msg.setDeviceID(NumberUtility.byteArray2Long(new byte[] { 0x43, 0x54, 0x17, 0x01, 0x41, 0x01, 0x00, 0x01 }));
		msg.setDeviceType((byte) 0x10);
		msg.setCommand((byte) 0x42);
		msg.setStatus((byte) 0x00);
		msg.setContent(content);
		msg.setChecksum(msg.generateCheckSum());
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// if send message without interrupt, it will appear TCP stick.
		// for (int i = 0; i < 5; i++) {
		// Thread.sleep(100);
		ctx.writeAndFlush(msg);
		// }
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		cause.printStackTrace();
		ctx.close();
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ControllerFrame msg) throws Exception {
		logger.debug("Object: {}", msg.toString());
		ctx.channel().close();

	}

}
